package mushystuff.dtb.web.endpoint;

import javax.xml.rpc.ServiceException;

import mushystuff.dtb.core.model.Product;
import mushystuff.dtb.core.model.UserStory;
import mushystuff.dtb.core.model.UserStory.Estimate;
import mushystuff.dtb.core.service.ProductService;
import mushystuff.dtb.web.vo.UserStoryVO;

import org.springframework.remoting.jaxrpc.ServletEndpointSupport;

public class BacklogServiceEndpoint extends ServletEndpointSupport {

    private static ProductService productService;

    @Override
    protected void onInit() throws ServiceException {
        if (productService == null) {
            productService = (ProductService) getWebApplicationContext()
                    .getBean("productService");
        }
    }
    
    public UserStoryVO[] getBacklog(long productId) {
        Product product = productService.getProduct(productId);
        return UserStoryVO.convert(product.getBacklog());
    }
    
    public void addUserStoryToBacklog(long productId, String story) {
        Product product = productService.getProduct(productId);
        UserStory userStory = new UserStory();
        userStory.setStory(story);
        productService.addUserStoryToBacklog(product, userStory);
    }
    
    public void modifyUserStory(long userStoryId, String story, String estimate) {
    	UserStory userStory = productService.getUserStory(userStoryId);
    	userStory.setStory(story);
    	userStory.setEstimate(Estimate.valueOf(estimate));
    	productService.createUpdateProduct(userStory.getProduct());
    }
    
    public String[] getEstimatesValues() {
    	Estimate[] estimatesArray = Estimate.values();
    	String[] estimates = new String[estimatesArray.length];
    	for(int i=0; i< estimatesArray.length; i++) {
    		estimates[i] = estimatesArray[i].name();
    	}
    	return estimates;
    }
}
